<script lang="ts" setup>
import type { OutsourceRecpt } from '#/api';

import { computed, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Button } from 'ant-design-vue';
import dayjs from 'dayjs';

import { useVbenForm } from '#/adapter/form';
import { addOutsourceRecpt, updateOutsourceRecpt } from '#/api';

import { useSchema } from './data';

const emit = defineEmits(['success']);
const formData = ref<OutsourceRecpt.Row>();
const title = ref<string>();
const showConfrimBtn = ref(true);
const [Form, formApi] = useVbenForm({
  wrapperClass: 'grid grid-cols-12',
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: useSchema(),
  showDefaultActions: false,
});

const getTitle = computed(() => {
  if (formData.value?.attr1 === '1') return '查看外协入库单信息';
  return formData.value?.attr1 === '2'
    ? '编辑外协入库单信息'
    : '新增外协入库单信息';
});
watch(getTitle, (newTitle) => {
  title.value = newTitle;
});
const [Modal, modalApi] = useVbenModal({
  class: 'w-[900px]',
  closeOnClickModal: false,
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (valid) {
      modalApi.lock();

      let data;
      await formApi.getValues().then((res) => {
        data = res;
      });
      try {
        await (formData.value?.recptId
          ? updateOutsourceRecpt(data!)
          : addOutsourceRecpt(data!));
        modalApi.close();
        emit('success');
      } finally {
        modalApi.lock(false);
      }
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<OutsourceRecpt.Row>();
      if (data) {
        // 回显格式化日期
        data.recptDate = dayjs(data.recptDate);
        formData.value = data;
        formApi.setValues(formData.value);
        showConfrimBtn.value = formData.value?.attr1 !== '1';
        modalApi.setState({
          showConfirmButton: showConfrimBtn.value,
        });
      }
    }
  },
});

function resetForm() {
  formApi.resetForm();
  formApi.setValues({});
}
</script>

<template>
  <Modal :title="getTitle">
    <Form class="mx-4" />

    <template #prepend-footer>
      <div class="flex-auto" v-if="showConfrimBtn">
        <Button type="primary" danger @click="resetForm"> 重置 </Button>
      </div>
    </template>
  </Modal>
</template>
